<!--* @param {string} clickSelectData 数据字典codeType-->
<!--* @param {string} clickSelectNameModel 用来显示中文的model容器，不填默认为ng-model-->
<!--* @param {string} clickSelectChangeFunc(click-select-change-func) 选项变更后的回调方法（含清空）-->
<!--* @param {string} setParamFunc(set-param-func="setCompanyParam()") 获取请求参数-->

<template>
  <div>
    <el-input
      ref="input"
      v-model="comName"
      :size="size"
      class="inputDbl"
      :placeholder="placeholder"
      :disabled="disabled"
      @focus="handleFocus"
      @blur="changeFun(comName)"
      @dblclick.native.stop.prevent="dblFun(comName)"
    />
    <div v-if="showFlag" id="layerBox" ref="layerBox">
      <div id="outerLayerBox">
        <div id="titleBoxStyle">
          <span id="titleStyle">请选择</span>
          <span id="chaStyle" @click="closeClick()">×</span>
        </div>
        <div id="dataBox" ref="dataBox">
          <el-tooltip
            v-for="(item,index) in dataList"
            :key="index"
            class="item"
            effect="light"
            :content="item.name"
            placement="right-end"
          >
            <span
              class="dataStyle"
              @mouseenter="enterEvent($event)"
              @mouseout="leaveEven($event)"
              @dblclick.stop="dbl($event)"
              @click="clickFun($event)"
            > {{ item.code }}---{{ item.name }} </span>
          </el-tooltip>
          <div v-if="tips" id="tipDivStyle">请选中后再点击确认!</div>
        </div>
        <div id="btnBoxStyle">
          <div id="sureBtnStyle" @click="sureClick()"> 确定</div>
          <div id="celBtnStyle" @click="cancelBtn()">取消</div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import './inputDbl.css'

export default {
  name: 'InputDblclick',
  // 拿到父组件里传过来的baseCode值
  model: {
    prop: 'value', // 这个字段，是指父组件设置 v-model 时，将变量值传给子组件的 msg
    event: 'input' // 这个字段，是指父组件监听 事件
  },
  // /此处必须定义和model的prop相同的props，因为v-model会传值给子组件（比如这里的value2）
  // props: ['parentPath', 'assignment', 'value', 'clickSelectData', 'setParam', 'clickSelectChangeFunc', 'disabled', 'size'],
  props: {
    formName: {},
    parentNode: {},
    parentPath: String,
    assignment: String,
    value: String,
    clickSelectData: String,
    setParam: Object,
    disabled: Boolean,
    size: String,
    clickCallFun: { // 双击的时候调用
      type: Function,
      default: null
    },
    clickSelectChangeFunc: { // 双击出来数据后调用，即选择数据的时候
      type: Function,
      default: null
    },
    passComFun: { // 判断是否传递了某个机构
      type: Function,
      default: null
    },
    scopeData: Object,
    placeholder: String,
    pageName: {},
    checkCode: {},
    defaultCode: String, // 默认code
    defaultCodeFun: { // 默认code赋值方法
      type: Function,
      default: null
    }
  },
  data() {
    return {
      dblFlag: false,
      oldComName: '',
      dataList: [],
      comName: '',
      comCode: '',
      showFlag: false,
      tips: false
    }
  },
  computed: {},
  watch: {
    'value': function() {
      // 在父组件清空model和code值时，将子组件的model和code值也都清空
      this.comName = this.value
      if (!this.value) {
        this.$emit('code', '')
      }
    },
    showFlag: function(n, o) {
      if (n === false) {
        // 执行校验
        this.$refs.input.focus()
        this.$refs.input.blur()
      }
    },
    defaultCode: function(n, o) {
      if (n) {
        this.postRequest('querySelectionDataListsByParams', [{ codeType: this.clickSelectData || '', pid: '' }]).then(data => {
          if (data.resultMsg == 'SUCCESS') {
            var dataList = data.resultObj[this.clickSelectData]
            for (let i = 0; i < dataList.length; i++) {
              if (this.defaultCode === dataList[i].code) {
                this.comName = dataList[i].name
                if (this.parentPath && this.assignment) {
                  var operateObj = this.formatAssignment(this.assignment)
                  this.$emit('code', {
                    parentPath: this.parentPath,
                    fieldName: operateObj.code,
                    value: dataList[i].code,
                    name: operateObj.name,
                    nameValue: dataList[i].name
                  })
                  return
                }
                break
              }
            }
          }
        }).catch(err => {

        })
      }
    }

  },
  mounted() {

  },
  created() {
    this.comName = this.value
    // defaultCode有值，循环遍历匹配code，拿到相应的name值
    debugger;
    if (this.defaultCode) {
      this.postRequest('querySelectionDataListsByParams', [{ codeType: this.clickSelectData || '', pid: '' }]).then(data => {
        if (data.resultMsg == 'SUCCESS') {
          var dataList = data.resultObj[this.clickSelectData]
          for (let i = 0; i < dataList.length; i++) {
            if (this.defaultCode === dataList[i].code) {
              this.comName = dataList[i].name
              if (this.parentPath && this.assignment) {
                var operateObj = this.formatAssignment(this.assignment)
                this.$emit('code', {
                  parentPath: this.parentPath,
                  fieldName: operateObj.code,
                  value: dataList[i].code,
                  name: operateObj.name,
                  nameValue: dataList[i].name
                })
                return
              }
              break
            }
          }
        }
      }).catch(err => {

      })
    }
    // 属性初始化
    // 'parentPath','assignment'
  },
  methods: {
    handleFocus() {
      this.oldComName = this.comName
    },
    showFun(comName) {
      if (this.clickCallFun) {
        this.clickCallFun()
        if (this.clickCallFun() == false) {
          return
        }
      }
      const loading = this.$loading({
        lock: true,
        text: '正在请求中...请稍等！！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'exportLoading'
      })

      debugger
      if (this.pageName && this.pageName === 'basicLawTemplate') {
        if (this.clickSelectData === 'Sales_Role') {
          this.postRequest('findRoleByCheckCode', {
            roleName: this.comName || '',
            checkCode: this.checkCode
          }).then(data => {
            loading.close()
            if (data.resultCode == '0000') {
              data.resultObj.forEach((item, index) => {
                item.name = item.roleName
                item.code = item.roleId
              })
              data.resultObj.unshift({
                name: '全部',
                code: 'all',
                roleId: 'all',
                roleName: '全部'
              })
              this.dataList = data.resultObj
              this.showFlag = true
            }
          }).catch(err => {
            loading.close()
          })
        }
        if (this.clickSelectData === 'Sales_Level') {
          var params = {}
          Object.assign(params, {
            checkCode: this.checkCode,
            levelName: this.comName || ''
          }, this.setParam)

          this.postRequest('findLevelByCheckCode', params).then(data => {
            loading.close()
            if (data.resultCode == '0000') {
              data.resultObj.forEach((item, index) => {
                item.name = item.levelName
                item.code = item.levelId
              })
              data.resultObj.unshift({
                name: '全部',
                code: 'all',
                levelId: 'all',
                levelName: '全部'
              })
              this.dataList = data.resultObj
              this.showFlag = true
            }
          }).catch(err => {
            loading.close()
          })
        }
        return
      }

      // 考核结果确认  查询角色
      if (this.clickSelectData === 'Sales_Role_CheckResult') {
        // baselawConfig/findRoleListByLikeDto
        var params = {}
        Object.assign(params, {
          baseLawId: this.scopeData.row.baseLawId,
          roleName: this.comName || ''
        }, this.setParam)
        this.postRequest('findRoleListByLikeDto', params).then(data => {
          loading.close()
          this.dataList = data.map((item, index) => {
            item.name = item.roleName
            item.code = item.roleId
            return item
          })
          this.showFlag = true
        }).catch(err => {
          loading.close()
        })

        return
      }
      if (this.clickSelectData === 'Sales_Level_CheckResult') {
        // baselawConfig/findRoleListByLikeDto
        var params = {}
        Object.assign(params, {
          baseLawId: this.scopeData.row.baseLawId,
          roleId: this.scopeData.row.finalRoleId || '',
          levelName: this.comName || ''
        }, this.setParam)
        this.postRequest('findBaseLawLevelByRoleId', params).then(data => {
          loading.close()
          this.dataList = data.map((item, index) => {
            item.name = item.levelName
            item.code = item.levelId
            return item
          })
          this.showFlag = true
        }).catch(err => {
          loading.close()
        })
        return
      }

      var paramObjInner = { 'codeType': this.clickSelectData || '', 'pid': this.comName || '' }

      var paramObjOutter = this.setParam

      // console.log(this.setParam)
      // es6合并两个对象
      var newObj = {}
      Object.assign(newObj, paramObjInner, paramObjOutter)

      // console.log(newObj)
      if (this.pageName && this.pageName === 'indicatorsLibrary') {
        newObj.validStatus = '1'
      }
      this.postRequest('querySelectionDataListsByParams', [newObj]).then(data => {
        loading.close()
        if (data.resultMsg == 'SUCCESS') {
          this.dataList = data.resultObj[this.clickSelectData]
          this.showFlag = true
        }
      }).catch(err => {
        loading.close()
      })
    },
    sendName(val) {
      this.$emit('input', val)
    },
    clearFun() {
      if (this.clickSelectChangeFunc) {
        this.clickSelectChangeFunc(this.scopeData)
      }

      this.comCode = ''
      this.comName = ''
      this.showFlag = false
      this.sendName(this.comName)
      this.sendCode() // 将code传给父组件
    },
    refreshCount() {
      this.tips = false
    },
    closeClick() {
      this.clearFun()
      // 选中的回调函数

      this.showFlag = false
    },
    enterEvent(ev) {
      var target = ev.target
      if (target.flag !== 1) {
        ev.target.style.background = '#F2F2F2'
      }
    },
    leaveEven(ev) {
      var targetEle = ev.target
      if (targetEle.flag !== 1) {
        ev.target.style.background = ''
      }
    },
    dbl(ev) {
      ev.target.style.background = '#189BEB'
      // ie的得到的ev.target.innerText末尾有空格，要去掉空格
      var content = ev.target.innerText.trim()
      var strIndexof = content.indexOf('---')
      this.comCode = content.substring(0, strIndexof)
      this.comName = content.substring(strIndexof + 3, content.length)
      this.showFlag = false
      this.sendName(this.comName)
      this.sendCode()
      // 选中的回调函数
      if (this.clickSelectChangeFunc) {
        this.clickSelectChangeFunc(this.scopeData)
      }
    },
    clickFun(ev) {
      $('.dataStyle').css('background', 'none')
      ev.target.style.background = '#189BEB'
      $('.dataStyle').attr('check', '')
      $(ev.target).attr('check', 'checked')
      var currentEle = ev.target
      currentEle.flag = 1
    },
    sureClick() { // 确定按钮
      var elm = $('.dataStyle[check=checked]')
      if (elm.length > 0) {
        this.showFlag = false
        var text = elm[0].innerText
        var index = text.indexOf('---')
        this.comCode = text.substring(0, index)
        this.comName = text.substring(index + 3, text.length)
        this.showFlag = false
        this.sendName(this.comName)
        this.sendCode() // 将code传给父组件
        // 选中的回调函数
        if (this.clickSelectChangeFunc) {
          this.clickSelectChangeFunc()
        }
      } else {
        this.tips = true
        // 定时器  几秒后移除提示
        window.setTimeout(this.refreshCount, 3000)
      }
    },
    cancelBtn() { // 取消按钮
      this.clearFun()
      // 选中的回调函数
    },
    sendCode() {
      // 传递当前scope对象
      if (this.scopeData) {
        this.$emit('code', {
          parentPath: this.parentPath,
          code: this.comCode,
          scopeData: this.scopeData
        })
        return
      }
      // 当页面获取各个代码比较多时
      if (this.parentPath && this.assignment) {
        var operateObj = this.formatAssignment(this.assignment)
        this.$emit('code', {
          parentPath: this.parentPath,
          fieldName: operateObj.code, // code字段
          value: this.comCode, // code值
          name: operateObj.name, // name字段
          nameValue: this.comName// name值
        })
        return
      }
      // 当页面获取各个代码少时
      this.$emit('code', this.comCode)
    },
    changeFun(val, dblFlag) {
      if (this.disabled) {
        return
      }

      if (this.comName === this.oldComName && !this.dblFlag) {
        return
      }
      if (this.passComFun) {
        this.passComFun()
        if (this.passComFun() == false) {
          return
        }
      }
      this.$emit('input', val)
      this.dblFlag = false
      this.showFun(val)
    },
    dblFun(val) {
      if (this.disabled) {
        return
      }
      if (this.passComFun) {
        this.passComFun()
        if (this.passComFun() == false) {
          return
        }
      }
      this.$emit('input', val)
      this.dblFlag = true
      this.$refs.input.blur()
    },

    // 格式化 Assignment 字段
    formatAssignment(str) {
      var arr = str.split(';')
      var formatObj = {}
      arr.forEach((item, index) => {
        if (item) {
          var itemArr = item.split('=')
          formatObj[itemArr[1]] = itemArr[0]
        }
      })
      return formatObj
    }

  }
}
</script>

<style scoped>
</style>
